package com.example.makerspace.manager;


import com.example.makerspace.dao.CategoryDAO;
import com.example.makerspace.domain.CategoryDO;
import com.example.makerspace.dto.CategoryDTO;
import com.example.makerspace.dto.Result;
import com.example.makerspace.enums.ResultCodeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.example.makerspace.service.impl.AdminServiceImpl.managerMap;

@Component
public class CategoryManager extends  BaseManager<CategoryDO, CategoryDTO>{
    @Resource
    private CategoryDAO categoryDAO;

    @PostConstruct
    public void init(){
        this.baseDAO = categoryDAO;
        managerMap.put("category", this);
    }

    public Result addCategory(CategoryDTO categoryDTO) {
        CategoryDO categoryDO = categoryDAO.selectByTypeAndName(categoryDTO);
        if(categoryDO != null){
            return Result.error(ResultCodeEnum.CATEGORY_EXIST);
        }
        return addDO(categoryDTO);
    }

    public Result updateCategory(CategoryDTO categoryDTO) {
        CategoryDO categoryDO = categoryDAO.selectById(categoryDTO.getId());
        if(categoryDO == null){
            return Result.error(ResultCodeEnum.CATEGORY_NOT_EXIST);
        }
        Optional.ofNullable(categoryDTO.getType()).ifPresent(categoryDO::setType);
        Optional.ofNullable(categoryDTO.getCategoryName()).ifPresent(categoryDO::setCategoryName);
        return updateDO(categoryDO);
    }


    public Result paramsList(Map<String, String> params) {
        List<CategoryDO> list = categoryDAO.list(params);
        List<CategoryDTO> dtoList = Optional.ofNullable(list).orElse(Collections.emptyList())
                .stream().map(this::convert2DTO).collect(Collectors.toList());
        return Result.success(dtoList);
    }
}
